<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"fengxun2017.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.13.2","exturl":false,"sidebar":{"position":"right","display":"hide","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文演示使用event group 来替代二值信号量，在任务和任务间，以及中断服务函数和任务间进行事件同步。">
<meta property="og:type" content="article">
<meta property="og:title" content="FreeRTOS-使用 event groups">
<meta property="og:url" content="http://fengxun2017.github.io/2023/01/31/FreeRTOS-use-event-group/index.html">
<meta property="og:site_name" content="fx">
<meta property="og:description" content="本文演示使用event group 来替代二值信号量，在任务和任务间，以及中断服务函数和任务间进行事件同步。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://fengxun2017.github.io/2023/01/31/FreeRTOS-use-event-group/sync-int-event.png">
<meta property="article:published_time" content="2023-01-30T16:00:00.000Z">
<meta property="article:modified_time" content="2023-02-03T13:42:41.981Z">
<meta property="article:author" content="feng xun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://fengxun2017.github.io/2023/01/31/FreeRTOS-use-event-group/sync-int-event.png">


<link rel="canonical" href="http://fengxun2017.github.io/2023/01/31/FreeRTOS-use-event-group/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://fengxun2017.github.io/2023/01/31/FreeRTOS-use-event-group/","path":"2023/01/31/FreeRTOS-use-event-group/","title":"FreeRTOS-使用 event groups"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>FreeRTOS-使用 event groups | fx</title>
  






  <script async defer data-website-id="" src=""></script>

  <script defer data-domain="" src=""></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <a target="_blank" rel="noopener" href="https://github.com/fengxun2017" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">fx</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-%E4%BD%BF%E7%94%A8event-group-%E5%9C%A8%E4%BB%BB%E5%8A%A1%E9%97%B4%E5%90%8C%E6%AD%A5%E4%BA%8B%E4%BB%B6"><span class="nav-number">1.</span> <span class="nav-text">1 使用event group 在任务间同步事件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-%E4%BD%BF%E7%94%A8event-group-%E5%9C%A8%E4%B8%AD%E6%96%AD%E5%92%8C%E4%BB%BB%E5%8A%A1%E9%97%B4%E5%90%8C%E6%AD%A5%E4%BA%8B%E4%BB%B6"><span class="nav-number">2.</span> <span class="nav-text">2 使用event group 在中断和任务间同步事件</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">feng xun</p>
  <div class="site-description" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">96</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">16</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://fengxun2017.github.io/2023/01/31/FreeRTOS-use-event-group/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="feng xun">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="fx">
      <meta itemprop="description" content="FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="FreeRTOS-使用 event groups | fx">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          FreeRTOS-使用 event groups
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-01-31 00:00:00" itemprop="dateCreated datePublished" datetime="2023-01-31T00:00:00+08:00">2023-01-31</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/FreeRTOS/" itemprop="url" rel="index"><span itemprop="name">FreeRTOS</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>7.6k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>10 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <center>
本文演示使用event group 来替代二值信号量，在任务和任务间，以及中断服务函数和任务间进行事件同步。
</center>

<span id="more"></span>

<hr>
<p>使用 <code>event group</code>需要在工程中添加源文件<code>event_groups.c</code>，并引用头文件<code>#include &quot;event_groups.h&quot; </code>。</p>
<h4 id="1-使用event-group-在任务间同步事件"><a href="#1-使用event-group-在任务间同步事件" class="headerlink" title="1 使用event group 在任务间同步事件"></a>1 使用event group 在任务间同步事件</h4><p>使用 <code>event group</code> 需要先创建：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">EventGroupHandle_t <span class="title function_">xEventGroupCreate</span><span class="params">( <span class="type">void</span> )</span>;</span><br></pre></td></tr></table></figure>
<p>创建成功时，该API 会返回一个用来标识该 <code>event group</code>的句柄。</p>
<p>当某个事件发生时，需要设置<code>event group</code>中表示该事件的对应位：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">EventBits_t <span class="title function_">xEventGroupSetBits</span><span class="params">( EventGroupHandle_t xEventGroup, <span class="type">const</span> EventBits_t uxBitsToSet )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>xEventGroup：xEventGroupCreate 的返回值，用来标识某个<code>event group</code>的句柄</li>
<li>uxBitsToSet：设置<code>event group</code>中的某些位，开发者定义每个位表示的对应事件。 32位处理器中，<code>event group</code>只有低24位可用，高8位是一些控制标记，<code>event group</code>内部使用的。</li>
</ul>
<p>当任务需要等待某个事件发生时，就是等待 <code>event group</code>中表示该事件的位被置位：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">EventBits_t <span class="title function_">xEventGroupWaitBits</span><span class="params">(<span class="type">const</span> EventGroupHandle_t xEventGroup,</span></span><br><span class="line"><span class="params">                                <span class="type">const</span> EventBits_t uxBitsToWaitFor,</span></span><br><span class="line"><span class="params">                                <span class="type">const</span> BaseType_t xClearOnExit,</span></span><br><span class="line"><span class="params">                                <span class="type">const</span> BaseType_t xWaitForAllBits,</span></span><br><span class="line"><span class="params">                                TickType_t xTicksToWait )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>xEventGroup：xEventGroupCreate 的返回值，用来标识某个<code>event group</code>的句柄</li>
<li>uxBitsToWaitFor：等待<code>event group</code>中的某些位被置位，开发者定义每个位表示的对应事件。</li>
<li>xClearOnExit：pdTRUE或pdFALSE。该值用来设置，当任务所等待的条件满足后（期望的事件发生了），该函数返回时，是否自动清除<code>event group</code> 中 uxBitsToWaitFor 所表示的那些位。设置为pdTRUE，表示自动清除，当任务进入阻塞态，等待一些事件发生（等待<code>event group</code>中的某些位被置位），当事件发生后，任务恢复就绪态，同时自动清零<code>event group</code>中事件所对应的位（类似于一些硬件中断发生后，需要主动清除硬件中断标记，避免重复触发的场景）</li>
<li>xWaitAllBits：设置为pdTRUE，表示要所有事件均发生（uxBitsToWaitFor中设置的那些位所表示的事件）。设置为pdFALSE，表示任意一个事件发生，即满足条件。</li>
<li>返回值：返回<code>event group</code>的值，当我们是等待多个事件中的任意一个发生时，就可以根据该值来判断是哪个事件发生了（参考后文在中断和任务间同步事件的代码）。注意，返值不受参数xClearOnExit 的影响，如果xClearOnExit&#x3D;pdTRUE，返回的值是自动清除操作执行前的值。</li>
</ul>
<p>为了演示，使用<code>event group</code>在任务间同步事件，我们创建 3 个任务，<code>task_a</code>、<code>task_b</code>和<code>task_c</code>。<br><code>task_b</code>和<code>task_c</code>每次执行工作前都需要先等待“事件”（<code>task_a</code>做完一些工作），“事件”未发生时，<code>task_b</code>和<code>task_c</code>就会阻塞。只有当<code>task_a</code>做完一些工作，设置“事件”，通知<code>task_b</code>和<code>task_c</code>可以运行了。<code>task_b</code>和<code>task_c</code>才能继续运行。</p>
<p>其逻辑如下所示：<br> <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">TASK_A:</span><br><span class="line">    <span class="keyword">while</span> <span class="number">1</span>:</span><br><span class="line">        <span class="keyword">do</span> something    <span class="comment">// 执行工作</span></span><br><span class="line">        <span class="built_in">set</span> event       <span class="comment">// 工作完成了，设置事件，通知 b,c 开始工作</span></span><br><span class="line"></span><br><span class="line">TASK_B:</span><br><span class="line">    <span class="keyword">while</span> <span class="number">1</span>:</span><br><span class="line">        wait event      <span class="comment">// 等待任务A工作完成 并设置事件</span></span><br><span class="line">        <span class="keyword">do</span> something</span><br><span class="line"></span><br><span class="line">TASK_C:</span><br><span class="line">    <span class="keyword">while</span> <span class="number">1</span>:</span><br><span class="line">        wait event      <span class="comment">// 等待任务A工作完成 并设置事件</span></span><br><span class="line">        <span class="keyword">do</span> something</span><br></pre></td></tr></table></figure></p>
<p>任务代码如下： task_b和task_c 可以共用一个任务函数，这里为了直观，每个任务单独写了一个。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用第 0 位来表示事件：task_a工作执行完</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> TASK_DONE_FLAG ( 1 &lt;&lt; 0 )    </span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_a</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line"></span><br><span class="line">    EventGroupHandle_t eg = (EventGroupHandle_t)pvParameters;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 延迟1秒，模拟 task_a 在处理一些工作</span></span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">        </span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;task_a done!\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 工作做完了，设置事件对应的位，通知task_b，task_c 可以运行了</span></span><br><span class="line">        xEventGroupSetBits(eg, TASK_DONE_FLAG);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_b</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    </span><br><span class="line">    EventGroupHandle_t eg = (EventGroupHandle_t)pvParameters;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 这里等待事件（task_a完成工作），如果task_a 还未设置这个信号量，</span></span><br><span class="line">        <span class="comment">// task_b 就会阻塞在该函数内部，直到task_a设置信号量，或者等待超过2秒</span></span><br><span class="line">        EventBits_t ret = xEventGroupWaitBits(eg, TASK_DONE_FLAG, pdTRUE, pdTRUE, pdMS_TO_TICKS(<span class="number">2000</span>));</span><br><span class="line">        <span class="keyword">if</span> (ret &amp; TASK_DONE_FLAG) &#123;</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;task_b start runing!\n&quot;</span>);</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;task_b done!\n&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_c</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    </span><br><span class="line">    EventGroupHandle_t eg = (EventGroupHandle_t)pvParameters;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 这里等待事件（task_a完成工作），如果task_a 还未设置这个信号量，</span></span><br><span class="line">        <span class="comment">// task_c 就会阻塞在该函数内部，直到task_a设置信号量，或者等待超过2秒</span></span><br><span class="line">        EventBits_t ret = xEventGroupWaitBits(eg, TASK_DONE_FLAG, pdTRUE, pdTRUE, pdMS_TO_TICKS(<span class="number">2000</span>));</span><br><span class="line">        <span class="keyword">if</span> (ret &amp; TASK_DONE_FLAG) &#123;</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;task_c start runing!\n&quot;</span>);</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;task_c done!\n&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ps：代码中，<code>task_b</code>和<code>task_c</code>调用xEventGroupWaitBits 等待事件时，均设置了自动清除 xClearOnExit&#x3D;pdTRUE。这不会有影响（即<code>task_b</code>的清除不会导致<code>task_c</code>判断不到事件发生了），因为 <code>event group</code>是遍历所有等待事件的任务，依次检查每个任务是否由于发生了某个事件，使得等待条件满足了，满足了就会恢复就绪态。所有任务遍历完后才会清除相应位。</p>
<p>main 函数实现如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用event group 在任务间同步事件</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line"></span><br><span class="line">    EventGroupHandle_t eg = xEventGroupCreate();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(<span class="literal">NULL</span> != eg) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (pdPASS == xTaskCreate(task_a, <span class="string">&quot;task_a&quot;</span>, <span class="number">100</span>, eg, <span class="number">1</span>, <span class="literal">NULL</span>)</span><br><span class="line">            &amp;&amp; pdPASS == xTaskCreate(task_b, <span class="string">&quot;task_b&quot;</span>, <span class="number">100</span>, eg, <span class="number">1</span>, <span class="literal">NULL</span>)</span><br><span class="line">            &amp;&amp; pdPASS == xTaskCreate(task_c, <span class="string">&quot;task_c&quot;</span>, <span class="number">100</span>, eg, <span class="number">1</span>, <span class="literal">NULL</span>))&#123;</span><br><span class="line">            </span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">            vTaskStartScheduler();</span><br><span class="line">        &#125; </span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;insufficient resource\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行结果如下：task_b、task_c每次等待task_a运行后才能运行。 并且每次task_a运行完，设置事件后，task_b、task_c都能收到事件，恢复就绪态并运行。这也体现了 <code>event group</code>的广播特性（区别于信号量每次只会让优先级最高的那个任务获恢复就绪）。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">task_a done!</span><br><span class="line">task_b start runing!</span><br><span class="line">task_b done!</span><br><span class="line">task_c start runing!</span><br><span class="line">task_c done!</span><br><span class="line">task_a done!</span><br><span class="line">task_b start runing!</span><br><span class="line">task_b done!</span><br><span class="line">task_c start runing!</span><br><span class="line">task_c done!</span><br></pre></td></tr></table></figure>

<h4 id="2-使用event-group-在中断和任务间同步事件"><a href="#2-使用event-group-在中断和任务间同步事件" class="headerlink" title="2 使用event group 在中断和任务间同步事件"></a>2 使用event group 在中断和任务间同步事件</h4><p>任务等待某个硬件相关的中断事件，是非常常见的应用场景。如任务等待按键事件，等待串口接收数据事件等。这里我们使用 <code>event group</code>来替代二值信号量，在中断服务函数和任务间同步事件。</p>
<p>我们创建一个任务，该任务等待按键事件和串口接收数据事件，任意一个事件发生都可以唤醒任务。因此，我们需要在按键中断处理函数&#x2F;串口中断处理函数中调用设置事件API，即<code>xEventGroupSetBits</code>的中断版本（带FromISR后缀）：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">BaseType_t <span class="title function_">xEventGroupSetBitsFromISR</span><span class="params">( EventGroupHandle_t xEventGroup,</span></span><br><span class="line"><span class="params">                                    <span class="type">const</span> EventBits_t uxBitsToSet,</span></span><br><span class="line"><span class="params">                                    BaseType_t *pxHigherPriorityTaskWoken )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>xEventGroup：创建api: xEventGroupCreate 返回的，用来标识某个<code>event group</code>的句柄</li>
<li>uxBitsToSet：设置<code>event group</code>中的某些位，开发者定义每个位表示的对应事件。 32位处理器中，<code>event group</code>只有低24位可用，高8位是一些控制标记，模块内部使用的。</li>
<li>pxHigherPriorityTaskWoken：该值的作用见后文代码中的注释。</li>
</ul>
<p>程序逻辑如下图所示：<br><img src="/2023/01/31/FreeRTOS-use-event-group/sync-int-event.png"></p>
<p><strong>注意</strong>：在文章<a href="https://fengxun2017.github.io/2023/01/13/FreeRTOS-event-group/">FreeRTOS-event groups 实现原理</a>的最后，我们提到过，当我们在中断服务函数中调用<code>xEventGroupSetBitsFromISR</code>来设置发生了某个事件时，实际的工作（设置event group相应位，遍历所有等待事件的任务查看是否有任务的等待条件满足了）会通过<a href="https://fengxun2017.github.io/2022/12/01/FreeRTOS-deferring-work/">延后执行机制</a>推迟到退出中断以后再执行。而内核提供的<a href="https://fengxun2017.github.io/2022/12/01/FreeRTOS-deferring-work/">延后执行机制</a>依赖<a href="https://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/">软件定时器服务任务</a>以及一些配置宏。所以，为了使用 API：<code>xEventGroupSetBitsFromISR</code>，需要在工程配置文件<code>FreeRTOSConfig.h</code>中添加如下配置：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> configUSE_TIMERS                1</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> INCLUDE_xTimerPendFunctionCall  1</span></span><br></pre></td></tr></table></figure>
<p>具体的任务和中断服务代码如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 第 0 位对应串口接收数据事件</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> UART_RECV_DATA  (1 &lt;&lt; 0)</span></span><br><span class="line"><span class="comment">// 第 1 位对应按键事件</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> BUTTON_PRESSED  (1 &lt;&lt; 1)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 定义一个全局的event group句柄变量</span></span><br><span class="line">EventGroupHandle_t eg;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 串口中断接收部分处理，与具体硬件平台相关</span></span><br><span class="line"><span class="comment">// 将 xEventGroupSetBitsFromISR 添加到自己硬件中断处理函数中即可</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">UARTE0_UART0_IRQHandler</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line">    BaseType_t higher_task_woken = pdFALSE;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (NRF_UART0-&gt;EVENTS_RXDRDY != <span class="number">0</span>)&#123;</span><br><span class="line">        <span class="comment">/// 我的硬件平台上，需要清0事件标志</span></span><br><span class="line">        NRF_UART0-&gt;EVENTS_RXDRDY = <span class="number">0</span>;</span><br><span class="line">        <span class="type">uint8_t</span> data = (<span class="type">uint8_t</span>)NRF_UART0-&gt;RXD;</span><br><span class="line"></span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;uart interrupt\n&quot;</span>);</span><br><span class="line">        <span class="comment">// 设置串口接收数据事件</span></span><br><span class="line">        xEventGroupSetBitsFromISR(eg, UART_RECV_DATA, &amp;higher_task_woken);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 如果higher_task_woken=True，表示设置事件操作，使得另一个等待该事件发生的更高优先级任务变为就绪了</span></span><br><span class="line">    <span class="comment">// 我们使用的是抢占式调度，只要有更高优先级的任务就绪，应该让其立刻运行。</span></span><br><span class="line">    <span class="comment">// 下面的代码就是，判断有更高优先级就绪时，就会设置任务切换中断，那么当前中断函数退出后，就会立刻触发任务切换，让最高优先级的就绪任务运行。</span></span><br><span class="line">    portYIELD_FROM_ISR(higher_task_woken);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 按键中断接收部分处理，与具体硬件平台相关</span></span><br><span class="line"><span class="comment">// 将 xEventGroupSetBitsFromISR 添加到自己硬件中断处理函数中即可</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">GPIOTE_IRQHandler</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line"></span><br><span class="line">    BaseType_t higher_task_woken = pdFALSE;</span><br><span class="line">    <span class="keyword">if</span> ( NRF_GPIOTE-&gt;EVENTS_PORT == <span class="number">1</span> )&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 我的硬件平台上，中断处理函数中要清除event,不然会导致一直产生中断</span></span><br><span class="line">        NRF_GPIOTE-&gt;EVENTS_PORT = <span class="number">0</span>;    </span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(IS_BUTTON_PRESSED(BUTTON_1)) &#123;</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;button interrupt\n&quot;</span>);</span><br><span class="line">            <span class="comment">// 设置按键事件</span></span><br><span class="line">            xEventGroupSetBitsFromISR(eg, BUTTON_PRESSED, &amp;higher_task_woken);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 如果higher_task_woken=True，表示设置事件操作，使得另一个等待该事件发生的更高优先级任务变为就绪了</span></span><br><span class="line">    <span class="comment">// 我们使用的是抢占式调度，只要有更高优先级的任务就绪，应该让其立刻运行。</span></span><br><span class="line">    <span class="comment">// 下面的代码就是，判断有更高优先级就绪时，就会设置任务切换中断，那么当前中断函数退出后，就会立刻触发任务切换，让最高优先级的就绪任务运行。</span></span><br><span class="line">    portYIELD_FROM_ISR(higher_task_woken);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 任务函数</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_func</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    </span><br><span class="line">    EventGroupHandle_t eg = (EventGroupHandle_t)pvParameters;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 这里等待按键事件或者串口接收数据事件</span></span><br><span class="line">        EventBits_t ret = xEventGroupWaitBits(eg, UART_RECV_DATA|BUTTON_PRESSED, pdTRUE, pdFALSE, portMAX_DELAY);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 根据返回值判断发生的事件</span></span><br><span class="line">        <span class="keyword">if</span> (ret &amp; UART_RECV_DATA) &#123;</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;event: received uart data\n&quot;</span>);</span><br><span class="line">        &#125; </span><br><span class="line">        <span class="keyword">if</span> (ret &amp; BUTTON_PRESSED) &#123;</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;event: button pressed\n&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>main函数代码：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用event group 在中断服务函数和任务间同步事件</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 硬件相关初始化</span></span><br><span class="line">    bsp_init();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建一个event group</span></span><br><span class="line">    eg = xEventGroupCreate();</span><br><span class="line">    <span class="keyword">if</span>(<span class="literal">NULL</span> != eg) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (pdPASS == xTaskCreate(task_func, <span class="string">&quot;task_func&quot;</span>, <span class="number">100</span>, eg, <span class="number">1</span>, <span class="literal">NULL</span>))&#123;</span><br><span class="line">            </span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">            vTaskStartScheduler();</span><br><span class="line">        &#125; </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;insufficient resource\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>输出如下所示：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">button interrupt            # 按键触发中断</span><br><span class="line">event: button pressed       # 按键事件使得任务恢复运行</span><br><span class="line">uart interrupt              # 串口接收到数据触发中断</span><br><span class="line">event: received uart data   # 串口接收数据事件使得任务恢复运行</span><br></pre></td></tr></table></figure>


<br>
ps：需要注意文章代码中的日志输出函数，产品代码中如果需要使用的话，需要考虑线程安全性（多任务安全性），因为中断/任务切换可能发生在另一个任务正在输出日志但还未输出完的时候，这就可能造成日志错乱

<br>
<br>
FreeRTOS交流QQ群-663806972
    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>feng xun
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://fengxun2017.github.io/2023/01/31/FreeRTOS-use-event-group/" title="FreeRTOS-使用 event groups">http://fengxun2017.github.io/2023/01/31/FreeRTOS-use-event-group/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2023/01/13/FreeRTOS-event-group/" rel="prev" title="FreeRTOS-event group 实现原理">
                  <i class="fa fa-chevron-left"></i> FreeRTOS-event group 实现原理
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2023/02/04/memory-ordering-cache-coherence/" rel="next" title="cache coherence">
                  cache coherence <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">feng xun</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">552k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">11:30</span>
  </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
